//
//  FrontViewController.m
//  KurtulusLaw
//
//  Created by phuc phuc on 12/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FrontViewController.h"
#import "Constant.h"
#import "CCommon.h"
#import "UserService.h"
#import "UserDTO.h"
#import "MBProgressHUD.h"


@interface FrontViewController()<UITextFieldDelegate>
{
	MBProgressHUD *_progressHUD;
	UserDTO *userDTO;
	UITextField *txtName;
	UITextField *txtSurName;
	UITextField *txtCompanyName;
	UITextField *txtTCID;
	UITextField *txtEmail;
	UITextField *txtTaxOffice;
	UITextField *txtTaxNo;
	UITextField *txtFax;
	UITextField *txtSkype;
	UITextField *txtPhone;
	UITextField *txtPhone1;
	UITextField *txtAddress;
	UITextField *txtCountry;
	UITextField *txtCity;
	UITextField *txtPostal;
	UITextField *txtWebsite;
	UITapGestureRecognizer *gesture;
}
@property (nonatomic,strong) UserDTO *userDTO;

// Private Methods:
- (IBAction)pushExample:(id)sender;

@end

@implementation FrontViewController
@synthesize tableViewProfile,userDTO;


#pragma mark - UITextFieldDelegate
-(void) hideKeyboard : (id) sender
{
	[txtPostal resignFirstResponder];
	[txtAddress resignFirstResponder];
	[txtCity resignFirstResponder];
	[txtCompanyName resignFirstResponder];
	[txtCountry resignFirstResponder];
	[txtEmail resignFirstResponder];
	[txtFax resignFirstResponder];
	[txtName resignFirstResponder];
	[txtPhone resignFirstResponder];
	[txtPhone1 resignFirstResponder];
	[txtPostal resignFirstResponder];
	[txtSkype resignFirstResponder];
	[txtSurName resignFirstResponder];
	[txtTaxNo resignFirstResponder];
	[txtTaxOffice resignFirstResponder];
	[txtTCID resignFirstResponder];
	[txtWebsite resignFirstResponder];
	[self.tableViewProfile removeGestureRecognizer: gesture];
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
	self.tableViewProfile.contentInset = UIEdgeInsetsMake(0, 0, 210, 0);
	[self.tableViewProfile addGestureRecognizer: gesture];
	return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	[self hideKeyboard:self];
	self.tableViewProfile.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
	return YES;
}


#pragma mark - UITableViewDataSource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
		return 6;
	}
	else
		return 4;
	
}

-(UITextField*)createTextfieldWithText  : (NSString*) _text
{
	UITextField *textfield= [[UITextField alloc] initWithFrame:CGRectMake(125, 6, 190, 20)];
	textfield.font = [UIFont systemFontOfSize:13.0];
	textfield.backgroundColor = [UIColor clearColor];
	textfield.text = _text;
	return textfield;
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
	UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    cell.userInteractionEnabled = NO;
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(8, 4, 110, 20)];
    lb.backgroundColor = [UIColor clearColor];
    lb.textColor = [UIColor grayColor];
    lb.font = [UIFont systemFontOfSize:13.0f];
	
	switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    lb.text = NSLocalizedString(@"Name", nil);
					txtName = [self createTextfieldWithText:userDTO.firstname ];
					txtName.delegate = self;
					[cell.contentView addSubview:txtName];
                    break;
                case 1:
                    lb.text = NSLocalizedString(@"Surname", nil);
					txtSurName = [self createTextfieldWithText:userDTO.lastname ];
					txtSurName.delegate= self;
					[cell.contentView addSubview:txtSurName];
                    break;
                case 2:
                    lb.text = NSLocalizedString(@"Company Name", nil);
					txtCompanyName = [self createTextfieldWithText:userDTO.company_name ];
					txtCompanyName.delegate = self;
					[cell.contentView addSubview:txtCompanyName];
                    break;
                case 3:
                    lb.text = @"T.C ID No";
					txtTCID = [self createTextfieldWithText:userDTO.tc_identity ];
					txtTCID.delegate = self;
					[cell.contentView addSubview:txtTCID];
                    break;
                case 4:
                    lb.text = NSLocalizedString(@"Tax Office", nil);
					txtTaxOffice = [self createTextfieldWithText:userDTO.tax_office ];
					txtTaxOffice.delegate = self;
					[cell.contentView addSubview:txtTaxOffice];
                    break;
                case 5:
                    lb.text = NSLocalizedString(@"Tax No", nil);
					txtTaxNo = [self createTextfieldWithText:userDTO.tax_number ];
					txtTaxNo.delegate = self;
					[cell.contentView addSubview:txtTaxNo];
                    break;
                default:
                    break;
            }
            [cell.contentView addSubview:lb];
            return cell;
        }
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                    lb.text = NSLocalizedString(@"Email", nil);
					txtEmail = [self createTextfieldWithText:userDTO.email ];
					txtEmail.delegate = self;
					[cell.contentView addSubview:txtEmail];
                    break;
                case 1:
                    lb.text = NSLocalizedString(@"Skype", nil);
					txtSkype = [self createTextfieldWithText:userDTO.skype ];
					txtSkype.delegate = self;
					[cell.contentView addSubview:txtSkype];
                    break;
                case 2:
                    lb.text = NSLocalizedString(@"Telephone 1", nil);
					txtPhone = [self createTextfieldWithText:userDTO.tel1];
					txtPhone.delegate = self;
					[cell.contentView addSubview:txtPhone];
                    break;
                case 3:
                    lb.text = NSLocalizedString(@"Telephone 2", nil);
					txtPhone1 = [self createTextfieldWithText:userDTO.tel2];
					txtPhone1.delegate = self;
					[cell.contentView addSubview:txtPhone1];
                    break;
                case 4:
                    lb.text = NSLocalizedString(@"Fax", nil);
					txtFax = [self createTextfieldWithText:userDTO.fax];
					txtFax.delegate = self;
					[cell.contentView addSubview:txtFax];
                    break;
                case 5:
                    lb.text = NSLocalizedString(@"Website", nil);
					txtWebsite = [self createTextfieldWithText:userDTO.website];
					txtWebsite.delegate = self;
					[cell.contentView addSubview:txtWebsite];
                    break;
                default:
                    break;
            }
            [cell.contentView addSubview:lb];
            return cell;
        }
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                    lb.text = NSLocalizedString(@"Address", nil);
					txtAddress = [self createTextfieldWithText:userDTO.address];
					txtAddress.delegate = self;
					[cell.contentView addSubview:txtAddress];
                    break;
                case 1:
                    lb.text = NSLocalizedString(@"City", nil);
					txtCity = [self createTextfieldWithText:userDTO.city];
					txtCity.delegate = self;
					[cell.contentView addSubview:txtCity];
                    break;
                case 2:
                    lb.text = NSLocalizedString(@"Country", nil);
					txtCountry = [self createTextfieldWithText:userDTO.country];
					txtCountry.delegate = self;
					[cell.contentView addSubview:txtCountry];
                    break;
                case 3:
                    lb.text = NSLocalizedString(@"Post Code", nil);
					txtPostal = [self createTextfieldWithText:userDTO.postcode];
					txtPostal.delegate = self;
					[cell.contentView addSubview:txtPostal];
                    break;
                default:
                    break;
            }
            [cell.contentView addSubview:lb];
            return cell;
        }
        default:
            break;
    }
    [cell.contentView addSubview:lb];
    return cell;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UILabel *label = [[UILabel alloc] init] ;
    label.frame = CGRectMake(0, 0, 305, 27);
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont boldSystemFontOfSize:15.0f];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"profile-section-bg-305x27"]];
    
    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
    
    switch (section) {
        case 0:
            label.text = [NSString stringWithFormat:@"  %@",NSLocalizedString(@"Profile", nil)];
            [view addSubview:label];
            return view;
            
        case 1:
            label.text =[NSString stringWithFormat:@"  %@", NSLocalizedString(@"Contact Details", nil)];
            [view addSubview:label];
            return view;
            
        case 2:
            label.text = [NSString stringWithFormat:@"  %@", NSLocalizedString(@"Address Details", nil)];
            [view addSubview:label];
            return view;
            
        default:
            return view;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 27;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 27.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableViewProfile deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"profile-cell-bg-305x27"]];

}
#pragma mark - View lifecycle
-(void) createView
{
	UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(55,6,280,30)];
    navLabel.text = NSLocalizedString(@"My Profile", nil);
    navLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    navLabel.textColor = [UIColor whiteColor];
    navLabel.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar addSubview: navLabel];
	
	if ([self.navigationController.parentViewController respondsToSelector:@selector(revealGesture:)] && [self.navigationController.parentViewController respondsToSelector:@selector(revealToggle:)])
	{
		UIPanGestureRecognizer *navigationBarPanGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self.navigationController.parentViewController action:@selector(revealGesture:)];
		[self.navigationController.navigationBar addGestureRecognizer:navigationBarPanGestureRecognizer];
        
        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10 , 0, 30, 46)];
        [backButton setImage:[UIImage imageNamed:kImageSlidebar34x46] forState:UIControlStateNormal];
        [backButton addTarget:self.navigationController.parentViewController action:@selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationController.navigationBar addSubview:backButton];
        
	}
    self.view.backgroundColor = [UIColor grayColor];
    self.tableViewProfile.backgroundColor = [UIColor grayColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-gray"] forBarMetrics:UIBarMetricsDefault]; 
    
    [self.tableViewProfile setBackgroundColor:[UIColor clearColor]];
    [self.tableViewProfile setBackgroundView:nil];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:kImageBackgroundForRightSideView]]];
}

-(void) getProfile : (NSString*) _session
{
	[UserService getProfileWithSessionID:_session :^(id dictionary, NSError *error) {
		if (error) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: [error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
			[alert show];
			[_progressHUD hide:YES];
		}
		else
		{
			@try {
				NSLog(@"%@",dictionary);
				if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
					self.userDTO = [[UserDTO alloc] initProfile: dictionary];
					NSLog(@"%@",self.userDTO);
					[self.tableViewProfile reloadData];
					[_progressHUD hide:YES];
				}
				else
				{
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Message", nil) message: NSLocalizedString(@"Can't get data from server", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
					[alert show];
					[_progressHUD hide:YES];
				}
			}
			@catch (NSException *exception) {
				[_progressHUD hide:YES];
			}
			@finally {
				//
			}
		}

	}];
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	_progressHUD.dimBackground = YES;
	_progressHUD.labelText = NSLocalizedString(@"Loading", nil);
	[self.view addSubview:_progressHUD];
	[self createView];
	NSString *sessionID = [CCommon shareSessionID];
	NSLog(@"session ID : %@",sessionID);
	[self getProfile: sessionID];
	// Create gesture recognizer
	gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
    
    // Set required taps and number of touches
    [gesture setNumberOfTapsRequired:1];
    [gesture setNumberOfTouchesRequired:1];
    
    
	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
	return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Example Code

- (IBAction)pushExample:(id)sender
{
	UIViewController *stubController = [[UIViewController alloc] init];
	stubController.view.backgroundColor = [UIColor whiteColor];
	[self.navigationController pushViewController:stubController animated:YES];
}
- (void)viewDidUnload {
    [self setTableViewProfile:nil];
    [super viewDidUnload];
}


@end
